const ANY = '\x01*\x02';

export default function fillWarnings({ tree, url, warnings }) {
	const fieldPath = new URL(url).pathname.slice(1).split('/').filter(Boolean);
	if (fieldPath.length === 0) {
		tree.warnings = warnings[0];
		tree.isAbnormal = true;
		return tree;
	}

	let subTree = tree.children;
	for (const fieldIdx in fieldPath) {
		const field = fieldPath[fieldIdx];
		if (!subTree) return tree;
		const any = subTree[ANY];
		let subs = Object.entries(subTree);
		if (any) {
			subs = subs.filter(x => x[0] !== ANY);
		}
		subs = subs.map(x => x[1]);
		let match = subs.find(x => {
			// console.log(Object.keys(x.patternMap).some(pattern => new RegExp('^' + pattern + '$', 'u').test(field)), x.value === field)
			// return Object.keys(x.patternMap).some(pattern =>
			// 	new RegExp('^' + pattern + '$', 'u').test(field)
			// );
			return x.value === field;
			// if (Object.keys(x.patternMap).some(pattern => new RegExp('^' + pattern + '$', 'u').test(field)) && x.value === field) {
			// 	return x
			// }
		});
		if (!match && any && any.value === field) {
			// match = Object.keys(any.patternMap).some(pattern =>
			// 	new RegExp(pattern, 'u').test(field)
			// );
			match = any;
		}
		if (!match) break;
		subTree = match.children;
		match.isAbnormal = true;
		if (+fieldIdx === fieldPath.length - 1) {
			match.warnings = warnings[0];
		}
	}
}
